Telegram Group & Telegram Channel
Глубокое клонирование реактивных объектов в Vue 3

Vue 3 использует Proxy для реактивности, что создает проблемы при попытке клонировать объекты. Стандартные методы работают не так, как ожидается:

const state = reactive({ user: { name: "Al" } });

// Проблемы:
const badCopy1 = { ...state }; // сохраняет Proxy-ссылки
const badCopy2 = JSON.parse(JSON.stringify(state)); // теряет методы и Proxy


3 рабочих способа

1. Комбинация toRaw + structuredClone

import { toRaw } from 'vue';

const original = reactive({ data: 123 });
const copy = structuredClone(toRaw(original));


2. Ручное глубокое копирование

function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
const clone = Array.isArray(obj) ? [] : {};
for (const key in obj) {
clone[key] = deepClone(obj[key]);
}
return clone;
}

const copy = reactive(deepClone(toRaw(original)));


3. Библиотечные решения

import { cloneDeep } from 'lodash-es';
const copy = reactive(cloneDeep(toRaw(obj)));


#tip #reactivity



tg-me.com/vuefaq/1187
Create:
Last Update:

Глубокое клонирование реактивных объектов в Vue 3

Vue 3 использует Proxy для реактивности, что создает проблемы при попытке клонировать объекты. Стандартные методы работают не так, как ожидается:

const state = reactive({ user: { name: "Al" } });

// Проблемы:
const badCopy1 = { ...state }; // сохраняет Proxy-ссылки
const badCopy2 = JSON.parse(JSON.stringify(state)); // теряет методы и Proxy


3 рабочих способа

1. Комбинация toRaw + structuredClone

import { toRaw } from 'vue';

const original = reactive({ data: 123 });
const copy = structuredClone(toRaw(original));


2. Ручное глубокое копирование

function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
const clone = Array.isArray(obj) ? [] : {};
for (const key in obj) {
clone[key] = deepClone(obj[key]);
}
return clone;
}

const copy = reactive(deepClone(toRaw(original)));


3. Библиотечные решения

import { cloneDeep } from 'lodash-es';
const copy = reactive(cloneDeep(toRaw(obj)));


#tip #reactivity

BY Vue-FAQ




Share with your friend now:
tg-me.com/vuefaq/1187

View MORE
Open in Telegram


Vue FAQ Telegram | DID YOU KNOW?

Date: |

What Is Bitcoin?

Bitcoin is a decentralized digital currency that you can buy, sell and exchange directly, without an intermediary like a bank. Bitcoin’s creator, Satoshi Nakamoto, originally described the need for “an electronic payment system based on cryptographic proof instead of trust.” Each and every Bitcoin transaction that’s ever been made exists on a public ledger accessible to everyone, making transactions hard to reverse and difficult to fake. That’s by design: Core to their decentralized nature, Bitcoins aren’t backed by the government or any issuing institution, and there’s nothing to guarantee their value besides the proof baked in the heart of the system. “The reason why it’s worth money is simply because we, as people, decided it has value—same as gold,” says Anton Mozgovoy, co-founder & CEO of digital financial service company Holyheld.

Telegram announces Search Filters

With the help of the Search Filters option, users can now filter search results by type. They can do that by using the new tabs: Media, Links, Files and others. Searches can be done based on the particular time period like by typing in the date or even “Yesterday”. If users type in the name of a person, group, channel or bot, an extra filter will be applied to the searches.

Vue FAQ from id


Telegram Vue-FAQ
FROM USA